# coding:utf-8
import sys
from typing import Dict, List

from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QTableWidgetItem
from PyQt6.QtGui import QColor, QFont

from views.template.table_template import MainTableTemplate, TableDataDto
from views.template.style_config import TableStyleConfig


class StyleExampleWindow(QMainWindow):
    """样式示例窗口"""

    def __init__(self):
        super().__init__()
        self.setWindowTitle("表格样式自定义示例")
        self.setGeometry(100, 100, 800, 600)

        # 创建中央组件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # 创建布局
        layout = QVBoxLayout(central_widget)

        # 创建自定义样式配置
        style_config = self.create_custom_style()

        # 创建表格模板
        table_template = MainTableTemplate(
            dataFun=self.get_table_data,
            datParamFun=self.get_params,
            style_config=style_config
        )

        # 添加到布局
        layout.addWidget(table_template)

    def create_custom_style(self) -> TableStyleConfig:
        """创建自定义表格样式"""
        # 创建基本样式配置
        style_config = TableStyleConfig(
            # 基本样式
            background_color="#FFFFFF",
            text_color="#333333",
            border_color="#CCCCCC",
            border_width=1,
            border_radius=8,
            padding=8,
            margin=10,
            font_family="微软雅黑",
            font_size=13,

            # 表格特定样式
            header_background="#4A86E8",
            header_text_color="#FFFFFF",
            header_font_weight="bold",
            header_height=45,

            row_height=40,
            alternate_row_color="#F5F9FF",
            use_alternate_colors=True,

            selection_color="#E0E8FF",
            hover_color="#F0F5FF",

            # 表格网格线
            grid_line_color="#E0E0E0",
            grid_line_width=1,
            show_horizontal_grid=True,
            show_vertical_grid=False,

            # 按钮样式
            button_background="#4A86E8",
            button_text_color="#FFFFFF",
            button_hover_background="#3A76D8",
            button_border_radius=4,

            # 列宽设置
            column_widths=[120, 150, 200, 150],
            stretch_last_column=True,
        )

        # 设置额外参数

        # 1. 设置列对齐方式
        column_alignments = {
            0: Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,  # 第一列左对齐
            1: Qt.AlignmentFlag.AlignCenter | Qt.AlignmentFlag.AlignVCenter,  # 第二列居中
            2: Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,  # 第三列右对齐
        }
        style_config.set_param("column_alignments", column_alignments)

        # 2. 设置按钮相关参数
        style_config.set_param("button_margin", 5)
        style_config.set_param("button_spacing", 10)
        style_config.set_param("button_width", 85)

        # 3. 设置单元格自定义样式函数
        def custom_cell_style(item: QTableWidgetItem, row_idx: int, col_idx: int, cell_data: str):
            # 根据单元格内容设置不同的样式
            if col_idx == 2 and cell_data.startswith("-"):
                # 负数显示为红色
                item.setForeground(QColor("#FF4D4D"))
                item.setFont(QFont("微软雅黑", 13, QFont.Weight.Bold))
            elif col_idx == 2 and float(cell_data) > 5000:
                # 大数值显示为绿色
                item.setForeground(QColor("#4CAF50"))
                item.setFont(QFont("微软雅黑", 13, QFont.Weight.Bold))

            # 为特定行设置背景色
            if row_idx == 0:
                item.setBackground(QColor("#FFFFE0"))  # 第一行淡黄色

        style_config.set_param("cell_style_func", custom_cell_style)

        # 4. 设置按钮自定义样式函数
        def custom_button_style(button, action_name):
            if action_name == "编辑":
                button.setStyleSheet("""
                    background-color: #4A86E8;
                    color: white;
                    border-radius: 4px;
                    padding: 5px 10px;
                """)
            elif action_name == "删除":
                button.setStyleSheet("""
                    background-color: #FF6B6B;
                    color: white;
                    border-radius: 4px;
                    padding: 5px 10px;
                """)
            elif action_name == "查看":
                button.setStyleSheet("""
                    background-color: #5CB85C;
                    color: white;
                    border-radius: 4px;
                    padding: 5px 10px;
                """)

        style_config.set_param("button_style_func", custom_button_style)

        return style_config

    def get_params(self) -> Dict[str, str]:
        """获取参数"""
        return {}

    def get_table_data(self, params: Dict[str, str]) -> TableDataDto:
        """获取表格数据"""
        # 表头
        headers = ["商品编号", "商品名称", "价格", "库存", "操作"]

        # 表格数据
        data = [
            ["P001", "笔记本电脑", "6999.00", "15"],
            ["P002", "智能手机", "3999.00", "28"],
            ["P003", "无线耳机", "899.00", "42"],
            ["P004", "平板电脑", "2899.00", "10"],
            ["P005", "智能手表", "1299.00", "35"],
            ["P006", "显示器", "-2499.00", "8"],
            ["P007", "机械键盘", "499.00", "20"],
            ["P008", "游戏鼠标", "299.00", "30"],
        ]

        # 操作按钮回调函数
        def edit_item(row_data: List[str]) -> str:
            return f"编辑商品: {row_data[1]}"

        def delete_item(row_data: List[str]) -> str:
            return f"删除商品: {row_data[1]}"

        def view_item(row_data: List[str]) -> str:
            return f"查看商品: {row_data[1]}"

        # 操作按钮配置
        actions = [
            {"查看": view_item},
            {"编辑": edit_item},
            {"删除": delete_item},
        ]

        return TableDataDto(table_header=headers, table_data=data, table_item_fun=actions)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = StyleExampleWindow()
    window.show()
    sys.exit(app.exec())
